import { useEffect, useState } from 'react'
import ConsentModal from '../components/ConsentModal.jsx'
import homeBG from '../assets/homeBG.png'
import { getUserStatus } from '../api/index.js';
import { useNavigate } from 'react-router-dom'

export const getParam = (name) => {
  let url = window.location.href;

  try {
    let params = url?.split('?')[1]?.split('#')[0]?.split('&') || [];
    for (let i = 0; i < params.length; i++) {
      let param = params[i];
      let key = param.split('=')[0];
      let value = param.split('=')[1];
      if (key === name) {
        return value;
      }
    }
  } catch (e) {
    console.error(e);
  }

  return '';
};

export default function Home() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);

  const openId = getParam('openId');
  console.log('User OpenId:', openId);
  if (openId) {
    window.sessionStorage.setItem('openId', openId);
  }

  useEffect(() => {
    const checkUserStatus = async () => {
      try {
        const response = await getUserStatus();
        const status = response.data?.data;
        console.log('User Status:', response.data);
        
        switch (status) {
          case 0: // 未同意用户隐私协议
            // 保留在首页，让用户点击按钮同意协议
            break;
          case 1: // 已同意用户隐私协议，未提交留资
            navigate('/form');
            break;
          case 2: // 已提交留资
            navigate('/success');
            break;
          default:
            // 默认情况保留在首页
            break;
        }
      } catch (error) {
        console.error('获取用户状态失败:', error);
        // 如果获取状态失败，也保留在首页
      } finally {
        setLoading(false);
      }
    };

    checkUserStatus();
  }, [navigate]);

  const handleAgree = () => {
    // 这里可以添加调用agreePrivacy接口的逻辑
    navigate('/form');
  };

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div
      className="w-[100vw] h-[100vh] relative overflow-hidden bg-cover bg-center"
      style={{
        backgroundImage: `url(${homeBG})`,
        backgroundSize: '100% auto',
        backgroundPosition: 'top',
        backgroundRepeat: 'no-repeat',
      }}
    >
      <ConsentModal  />
    </div>
  )
}